#!/usr/bin/env python3
"""
UmaInsight Backend Python
Main FastAPI application entry point
"""

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
import logging
import os

from app.core.config import settings
from app.core.database import init_databases
from app.api.v1 import auth, teams, telemetry, search, directory_tree, directories


# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI):
    """Application lifespan manager"""
    # Startup
    logger.info("Starting UmaInsight Backend Python...")
    await init_databases()
    logger.info("Databases initialized successfully")

    yield

    # Shutdown
    logger.info("Shutting down UmaInsight Backend Python...")


# Create FastAPI application
app = FastAPI(
    title="UmaInsight Backend API",
    description="UMA/UKM Analytics Platform Backend",
    version="2.0.0",
    lifespan=lifespan
)

# Configure CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.ALLOWED_HOSTS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


# Include routers
app.include_router(auth.router, prefix="/api/v1/auth", tags=["Authentication"])
app.include_router(teams.router, prefix="/api/v1/teams", tags=["Teams"])
app.include_router(telemetry.router, prefix="/api/v1", tags=["Telemetry"])
app.include_router(search.router, prefix="/api/v1/search", tags=["Search"])
app.include_router(directory_tree.router, prefix="/api/v1/directory", tags=["Directory Tree"])
app.include_router(directories.router, prefix="/api/v1/directories", tags=["Directories"])


@app.get("/")
async def root():
    """Root endpoint"""
    return {
        "message": "UmaInsight Backend Python",
        "version": "2.0.0",
        "status": "running"
    }


@app.get("/health")
async def health_check():
    """Health check endpoint"""
    return {
        "status": "healthy",
        "environment": settings.ENVIRONMENT
    }


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8000,
        reload=settings.DEBUG,
        log_level="info"
    )